const API_BASE_URL = "http://127.0.0.1:8000";

// 获取存储的 token
function getToken() {
  const token = localStorage.getItem("token");
  return token;
}

// 设置 token
function setToken(token) {
  localStorage.setItem("token", token);
}

// 清除 token
function clearToken() {
  localStorage.removeItem("token");
}

// 通用的 fetch 函数
async function fetchApi(endpoint, method = "GET", body = null, headers = {}) {
  const options = {
    method,
    headers: {
      "Content-Type": "application/json",
      ...headers,
    },
    credentials: "include",
    mode: "cors",
  };

  const token = getToken();
  if (token) {
    options.headers["Authorization"] = `Bearer ${token}`;
  }

  if (body) {
    options.body = JSON.stringify(body);
  }

  const response = await fetch(`${API_BASE_URL}${endpoint}`, options);
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  return await response.json();
}

// 用户登录
export async function login(username, password) {
  const response = await fetchApi("/login", "POST", { username, password });

  if (response.data.token) {
    setToken(response.data.token);
  }
  return response;
}

// 用户注册
export async function register(username, realname, email, password) {
  return fetchApi("/register", "POST", { username, realname, email, password });
}

// 修改密码
export async function changePassword(oldPassword, newPassword) {
  return fetchApi("/change-password", "POST", { oldPassword, newPassword });
}
 